<template>
  <div class="import-components">
    <el-upload
      class="upload"
      :action="action"
      :headers="headers"
      :show-file-list="false"
      :on-success="onSuccess"
      :before-upload="beforeUpload"
    >
      <el-button :type="btnType">{{ btnText }}</el-button>
    </el-upload>
  </div>
</template>
<script>
export default {
  props: {
    url: {
      type: String,
      default: "",
    },
    // 图片上传请求头
    headers: {
      type: Object,
      default: function () {
        return {
          "X-Auth0-Token": localStorage.getItem("token"),
        };
      },
    },
    // 按钮上传的文案
    btnText: {
      type: String,
      default: "从文件导入",
    },

    btnType: {
      type: String,
      default: "primary",
    },

    // 允许的上传格式
    format: {
      type: Array,
      default: () => ["xls", "xlsx", "XLS", "XLSX"],
    },

    // 文件大小的限制
    fileSize: {
      type: Number,
      default: 1048576 * 1024,
    },
  },
  data() {
    return {};
  },
  computed: {
    action() {
      return process.env.VUE_APP_BASE_URL + this.url;
    },
  },
  methods: {
    onSuccess(response) {
      this.$emit("change", response);
    },

    // 上传文件格式大小拦截
    beforeUpload(file) {
      if (this.format.length === 0) return true;

      const fileFormat = file.name.substring(file.name.lastIndexOf(".") + 1);
      const formatState = this.format.indexOf(fileFormat) > -1;
      if (!formatState) {
        this.$message({
          message: `只允许上传${this.format.join()}格式的文件，请重新选择！`,
          type: "warning",
        });
      }

      const fileSizeState = this.fileSize > file.size;
      if (!fileSizeState) {
        this.$message({
          message: "上传文件过大，请重新选择!",
          type: "warning",
        });
      }

      return formatState && fileSizeState;
    },
  },
};
</script>
<style lang="scss">
.import-components {
  display: inline-block;
  .upload {
  }
}
</style>
